#!/usr/bin/env python
# -*- coding: utf-8 -*-

# ModBus_Thread
# start a thread for polling a set of registers, display result on console
# exit with ctrl+c

#   yes  self.c.read_input_registers()
#   yes  self.c.read_coils()
#   yes  self.c.read_holding_registers()
#   yes  self.c.write_multiple_coils()
#   yes  self.c.write_multiple_registers()

#   self.c.read_discrete_inputs()
#   self.c.write_single_coil()
#   self.c.write_single_register()
import time
from threading import Lock

from PyQt5.QtCore import QObject
from pyModbusTCP.client import ModbusClient
import Globalist as gl
import lib.applets as sApp


# ModBus polling thread for PLC communication
class QPollThread(QObject):
    def __init__(self, threadNum=None):
        super().__init__()
        # init a thread lock
        self.regs_lock = Lock()
        self.c = None
        self.SERVER_PORT = 502
        aa = threadNum.split("-")
        self.strKey = aa[1]
        self.strIp = aa[2]
        self.modBusAddress = int(aa[3])
        ''''''

    def polling_thread(self):
        # polling loop
        try:
            self.c = ModbusClient(host=self.strIp, port=self.SERVER_PORT, timeout=1)
        except BaseException as e:
            print(e)
            return
        while True:
            if not self.c.is_open():
                self.c.open()
            if True:
                # do ModBus reading on socket
                reg_PowerList = self.c.read_holding_registers(self.modBusAddress, 2)
                if reg_PowerList:
                    try:
                        aa2 = 0.0
                        if self.modBusAddress == 16415:
                            aa = sApp.hex_2_f(sApp.To_hex_str(reg_PowerList[1]), sApp.To_hex_str(reg_PowerList[0])) * 120
                            aa2 = round(aa, 2)
                        elif self.modBusAddress == 106:
                            aa = sApp.SWd2DWd(reg_PowerList[1], reg_PowerList[0])
                            aa2 = float(int(aa)) / 100.0
                        gl.global_var["watt_hour_meter_ip"][int(self.strKey)] = [self.strIp, self.modBusAddress, aa2]
                    except BaseException as e:
                        print(e)
            '''处理信号'''
            pass
            # 0.1s before next polling
            time.sleep(0.1)

    def stopPoll(self):
        pass

    def startPoll(self):
        pass

    def startThread(self):
        print("开始")
        # start polling thread
        sk = self.polling_thread()
        # set daemon: polling thread will exit if main thread exit
        sk.daemon = True
        sk.start()
        print("结束")


if __name__ == '__main__':
    tpj = QPollThread()
    tpj.startThread()
